const os = require("os");
const Koa = require("koa");
const Router = require("koa-router");
const Bodyparser = require("koa-bodyparser")

const app = new Koa();
const router = new Router();
const { Search } = require("./search");

let dirPathList = [
    "C:/ProgramData/Microsoft/Windows",
    os.homedir() + "/AppData/Roaming/Microsoft/Windows/Start Menu",
    "F:/桌面/1"
];

let config = {
    dataBase: __dirname + "/search.db"
};

let search = new Search(dirPathList, config);
let messageHandler = {
    refresh: () => {
        search.refresh();
        process.send({
            type: "refresh",
            args: [
                search.consume,
                search.lastUpdate
            ]
        });
    }
}

router.post("/search", async function (ctx) {
    let { keyWord, setting } = ctx.request.body;
    setting = JSON.parse(setting);
    let filter = setting.filter || undefined;
    if (filter && filter != "") {
        filter = new RegExp(`(${ setting.filter.split("\n").filter(word => word != "").join(")|(") })`);
    }
    ctx.response.body = JSON.stringify({
        list: search.extension(setting.extensions ? setting.extensions.split(",") : undefined, keyWord, {
            filter: filter,
            modifiers: "i"
        }),
        consume: search.consume,
        lastUpdate: search.lastUpdate
    });
});

router.get("/refresh", async function (ctx) {
    search.refresh();
    ctx.response.body = JSON.stringify({
        success: true
    });
});
app.use(Bodyparser());
app.use(router.routes()).use(router.allowedMethods());

app.listen(1227, () => {
    console.log("start listen port 1227....");
});